package android.com.app;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.com.app.DBAdapter.Table;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

/* The activity that handles audio recording and playback */
public class audiohandler extends Activity{
	
	
    /* To connect to the database for the table that stores audio files corresponding to images */
	private DBAdapter dba;
	MediaRecorder recorder;
	MediaPlayer player;
	private static String img_title;
	private static Bundle extras;
	private ListView audioListView;
    private static String audioFilename;
    private Button recordbtn;
    private Button stopbtn;
    private boolean isRecording; //some flags
    private boolean isPlaying;
    private TextView tv;
    private TextView status;
    ArrayList<String> fileList;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);

	    extras=getIntent().getExtras();  
	    img_title = extras.getString("Title"); //Get the title of the current image
	    
	    /******** SET THE LAYOUT ***********/
	    
	    
	    audioListView = new ListView(this);
	    LinearLayout ll = new LinearLayout(this);
	    tv = new TextView(this);
	    status = new TextView(this);
	    LinearLayout buttonll =  new LinearLayout(this);
	    
	    recordbtn = new Button(this);
	    recordbtn.setText("Record");
	   // recordbtn = (Button) findViewById(R.id.rcdbtn);
	    stopbtn =new Button(this);
	    stopbtn.setText("Stop");
	    buttonll.setOrientation(LinearLayout.HORIZONTAL);
	    buttonll.addView(recordbtn);
	    buttonll.addView(stopbtn);
	    recordbtn.setWidth(250);
	    stopbtn.setWidth(250);
	    
	    ll.setOrientation(LinearLayout.VERTICAL);
	    ll.addView(buttonll);
	    ll.addView(tv);
	    ll.addView(audioListView);
	    ll.addView(status);
	    dba=new DBAdapter(this);
	    
	 
	    stopbtn.setEnabled(false);
	    
	    /************** SET THE LISTENERS *************/
	    
	    recordbtn.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View view){
   			
        		try{
        			stopbtn.setEnabled(true);
        			recordbtn.setEnabled(false);
        			audioListView.setEnabled(false);
        			startAudioRec();
        		}catch(FileNotFoundException e)
        		{
        			e.printStackTrace();
        		}

        	}
        });
	    
	    stopbtn.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View view){
        		try{
        	    	if(isRecording){
        	    			stopAudioRec();
        	    			isRecording=false;
        	    	}
        	    	if(isPlaying){
        	    		 	stopAudioPlay();
        	    		 	isPlaying=false;
        	    	}
        	    	status.setText("Idle");
        	    	audioListView.setEnabled(true);
        	    	stopbtn.setEnabled(false); //Dont need stop now
        
        	    	
        	    	
        	   recordbtn.setEnabled(true);

        		}
        		catch(Exception e){
        			e.printStackTrace();

        		}
        	}
        });
	    
	   audioListView.setOnItemClickListener(new OnItemClickListener(){
		   
		   public void onItemClick(AdapterView parent,View v,int position, long id){
			   
			   stopbtn.setEnabled(true);
   			   recordbtn.setEnabled(false);
   			   audioListView.setEnabled(false);
			   startAudioPlay(position);
			   
		   }
	   		});

			   
	   /********** SET THE LAYOUT IN THE VIEW **********/
		   setContentView(ll);
		   
	   /********* QUERY THE DB AND GET ALL ASSOCIATED AUDIO FILES ********/
	       getAudioFiles();
	}
	
	
    protected void onPause() {
    	super.onPause();
    	if(isRecording){
    		stopAudioRec();
    	}
    	else if(isPlaying){
    		stopAudioPlay();
    	}
    }
    protected void onResume(){
    	super.onResume();	
    }
    
    /******* HANDLE RECORDING *********/
    
	public boolean startAudioRec() throws FileNotFoundException{	
		
		isRecording=true;
    	status.setText("Recording....");

		recorder = new MediaRecorder();
	    audioFilename = "AUD"+String.valueOf(System.currentTimeMillis());

	    recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
	    recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
	    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
	    recorder.setOutputFile("/sdcard/"+audioFilename+".3gp");
	    recorder.prepare();
	    recorder.start();
	    
	    return isRecording; //Return true it indicate recording is going on
	    
	}
	
	/********** HANDLE STOP RECORDING ***********/

	public boolean stopAudioRec(){
		recorder.stop();
	    recorder.release();	
	    
	    //Add to DB
	    dba.open();
	    dba.AddAudio(img_title, "/sdcard/"+audioFilename+".3gp");
	    dba.close();
	    getAudioFiles(); 	//This should refresh the list
	    isRecording=false;
	    return isRecording;
	}
	
	/*************** HANDLE PLAYBACK *****************/
	
	public boolean startAudioPlay(int sIndex){
		isPlaying = true;
    	status.setText("Playing....");

		 MediaPlayer player = new MediaPlayer();
		 try{
			 //Try to play the file or catch fileIO exception
			 player.setDataSource(fileList.get(sIndex));
			 player.prepare();
			 player.start();
			 
			 //To perform when playback has completed
			 player.setOnCompletionListener(new OnCompletionListener(){

				public void onCompletion(MediaPlayer mp) {
					stopbtn.performClick();
				}
						 
			 });
		 }catch(IOException ioe){
			 
			 //In case this file has been deleted from the SDCARD, handle it and update our database
			 status.setText("The file has been deleted.");
			 dba.DeleteEntry(Table.AUDIO, fileList.get(sIndex));
			 fileList.remove(sIndex);
			 ioe.printStackTrace();
			 isPlaying=false;
		 }

		return isPlaying;
	}
	
	
	/******* STOP AUDIO PLAYBACK *******/
	
	public boolean stopAudioPlay(){
		
		isPlaying = false;
		if(player!=null) {
			player.stop();
			player.release();
		}
		return isPlaying;
	}
	
	//Fetches the current audio files associated with this image from the DB and adds it to the list view
	
	public void getAudioFiles(){
		//query the database to get all the audio files to 	
		dba.open();
		
		Cursor cur = dba.fetch(Table.AUDIO,img_title);
		
	    fileList = new ArrayList<String>();
	    ArrayList<String> dispList = new ArrayList<String>();
	    
	    if(cur!=null&&cur.getCount()==0){
	    	tv.setText("No audio files associated with this image");
	    	
	    }
	    else{
	    	
		    tv.setText("The following audio files are associated with this image. Click on it to play.");

	    }
	    int count=1;
		
		while(cur!=null && cur.getCount()>0){
			
			fileList.add(cur.getString(cur.getColumnIndexOrThrow("audio")));
			dispList.add("Audio"+count++);						
			if(! cur.moveToNext())
				break;
			
		}
			
		ArrayAdapter<String> audiolistadapter = new ArrayAdapter<String>(this, R.layout.audiolist_row, dispList);
		audioListView.setAdapter(audiolistadapter);
		dba.close();
		
	}
	
	protected void onDestroy() {
		super.onDestroy();
		if(isRecording){
    		stopAudioRec();
    	}
    	else if(isPlaying){
    		stopAudioPlay();
    	}
	}
	
	private static final int GAL_ID = Menu.FIRST;
	private static final int CAM_ID = Menu.FIRST+1;
    
    
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
        case GAL_ID:
        	startActivity(new Intent( this, thumbviewer.class));
            return true;
        case CAM_ID:
        	startActivity(new Intent( this, aPics.class));
        	return true;
        }
        return super.onMenuItemSelected(featureId, item);
    }
    
}
